package com.base.im.server.netty.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class ClientServer {
	
	private  final Logger logger = LoggerFactory.getLogger(ClientServer.class);

	private final String HOST = System.getProperty("host", "127.0.0.1");  
	
	private final int PORT = Integer.parseInt(System.getProperty("port", "8007")); 
	
	private final EventLoopGroup group = new NioEventLoopGroup();  ;  
  
    public  void bind(){  
    	
    	try {
    		
    		// Configure the client.  
            
            try {  
                Bootstrap b = new Bootstrap();  
                b.group(group)  
                 .channel(NioSocketChannel.class)  
                 .option(ChannelOption.TCP_NODELAY, true)  
                 .handler(new ChannelInitializer<SocketChannel>() {  
                     @Override  
                     public void initChannel(SocketChannel ch) throws Exception {  
                         ChannelPipeline p = ch.pipeline();  
                         p.addLast("decoder", new StringDecoder());  
                         p.addLast("encoder", new StringEncoder());  
                         p.addLast(new ClientServerHandler());  
                     }  
                 });  
      
                ChannelFuture future = b.connect(HOST, PORT).sync();  
                logger.error("服务端启动 端口为"+PORT);
                
                Channel channel = future.channel();
                ClientSession.setSession(channel);
                
//                channel.writeAndFlush("Hello Netty Server ,I am a common client 1");  
//                future.channel().writeAndFlush("Hello Netty Server ,I am a common client 2");  
//                future.channel().closeFuture().sync(); 
			} catch (Exception e) {
				logger.error("客户端启动异常 原因["+e+"]");
			}
    	
        } finally {  
//            group.shutdownGracefully();  
        }  
    } 
    
    
    
    
    public static void main(String[] args) {
    	ClientServer clientServer = new ClientServer();
    	clientServer.bind();
		
	}
	
}
